package util;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import model.Ticket;

public class TicketDAO {

	public void addTicket(Ticket ticket) throws SQLException {
		Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.save(ticket);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
	}

	public void updateTicket(Ticket ticket) throws SQLException {
		Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.update(ticket);
            session.getTransaction().commit();
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }

	}

	public Ticket getTicketById(Long id) throws SQLException {
		Session session = null;
        Ticket ticket = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            ticket = (Ticket) session.load(Ticket.class, id);
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return ticket;
	}

	@SuppressWarnings("unchecked")
	public List<Ticket> getAllTickets() throws SQLException {
		Session session = null;
        List<Ticket> ticket = new ArrayList<Ticket>();
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            ticket = session.createCriteria(Ticket.class).list();
        } catch (Exception e) {
        	e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return ticket;
	}

	public void deleteTicket(Ticket ticket) throws SQLException {
		 Session session = null;
         try {
             session = HibernateUtil.getSessionFactory().openSession();
             session.beginTransaction();
             session.delete(ticket);
             session.getTransaction().commit();
         } catch (Exception e) {
        	 e.printStackTrace();
         } finally {
             if (session != null && session.isOpen()) {
                 session.close();
             }
         }
   }  
}

